package net.wsfcp.android.http.mvp.model;

import android.support.annotation.NonNull;
import android.util.Log;

import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;

import net.wsfcp.android.base.BaseApplication;
import net.wsfcp.android.base.BaseHttpResult;
import net.wsfcp.android.base.BaseModel;
import net.wsfcp.android.bean.requestbean.ReqUpdateUserBean;
import net.wsfcp.android.bean.resultbean.QiniuUploadImageBean;
import net.wsfcp.android.http.UrlHelper;
import net.wsfcp.android.http.exception.ApiException;
import net.wsfcp.android.http.exception.ErrorType;
import net.wsfcp.android.http.exception.ExceptionEngine;
import net.wsfcp.android.http.exception.ServerException;
import net.wsfcp.android.http.mvp.subscriber.CommonSubscriber;
import net.wsfcp.android.http.mvp.subscriber.ErrorSubscriber;
import net.wsfcp.android.http.mvp.transformer.CommonTransformer;
import net.wsfcp.android.qiniu.QiniuUtil;
import net.wsfcp.android.utils.SpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by Shaoboyang on 2018/12/14.
 * 主要做一些数据处理呀,网路请求
 */

public class InfoModel extends BaseModel {


    //上传头像
    public void uploadImg(File file, String fileName, @NonNull final UploadImgInfoHint
            infoHint) {

        if (infoHint == null)
            throw new RuntimeException("InfoHint不能为空");


        QiniuUtil.getInstance().getUploadManager().put(file, fileName, SpUtils.getInstance().getImgToken(), new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject res) {
                //res包含hash、key等信息，具体字段取决于上传策略的设置
                if (info.isOK()) {
                    Gson gson = new Gson();
                    QiniuUploadImageBean bean = gson.fromJson(res.toString(), QiniuUploadImageBean.class);
                    infoHint.uploadImgSuccessInfo(bean);

                } else {
                    try {
                        String msg = res.getString("error");
                        infoHint.uploadImgFailInfo(msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        infoHint.uploadImgFailInfo("失败");
                    }

                }

            }
        }, null);
    }

    //保存用户信息
    public void updateUser(@NonNull ReqUpdateUserBean bean, @NonNull final UpdateUserInfoHint
            infoHint) {

        if (infoHint == null)
            throw new RuntimeException("InfoHint不能为空");

        Gson gson = new Gson();
        String obj = gson.toJson(bean);
        Log.e("json数据", obj);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), obj);
        httpService.updateUser(UrlHelper.UPDATE_USER + SpUtils.getInstance().getToken(), body)
                .enqueue(new Callback<BaseHttpResult>() {
                    @Override
                    public void onResponse(Call<BaseHttpResult> call, Response<BaseHttpResult> response) {
                        if (response != null && response.body() != null) {
                            if (response.body().getResultCode() == ErrorType.SUCCESS) {
                                infoHint.updateUserSuccessInfo();
                            } else {
                                infoHint.updateUserFailInfo(response.body().getResultMsg());
                            }
                        } else {
                            infoHint.updateUserFailInfo("失败");
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseHttpResult> call, Throwable t) {
                        ServerException e = ExceptionEngine.handleException(t);
                        infoHint.updateUserFailInfo(e.getMessage());
                    }
                });

//                .compose(new CommonTransformer())
//                .subscribe(new CommonSubscriber(BaseApplication.getContext()) {
//                    @Override
//                    public void accept(Object o) {
//                        infoHint.updateUserSuccessInfo();
//                    }
//
//
//                }, new ErrorSubscriber<Throwable>(BaseApplication.getContext()) {
//                    @Override
//                    public void accept(Throwable e) {
//                        if(e instanceof ServerException)
//                        infoHint.updateUserFailInfo(((ServerException)e).message);
//                    }
//                });
    }


    //通过接口产生信息回调
    public interface UploadImgInfoHint {
        //登录
        void uploadImgSuccessInfo(QiniuUploadImageBean bean);

        void uploadImgFailInfo(String str);


    }


    public interface UpdateUserInfoHint {
        //登录
        void updateUserSuccessInfo();

        void updateUserFailInfo(String str);


    }

}
